import editForm from "../form/index.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import { getMenuList, addMenu, upMenu, delMenu } from "@/api/system/menu";
import { type Ref, h, ref, computed, reactive, onMounted, watch } from "vue";
import { cloneDeep } from "@pureadmin/utils";

const tabType = ref(1);
const treeLoading = ref(true);
const treeData = ref([]);

export function useUser(tableRef?: Ref, treeRef?: Ref) {
  const form = reactive({
    parentId: null,
    pageNum: 1,
    pageSize: 10
  });
  const currentTreeData = reactive({
    id: null,
    menuName: "",
    isLeaf: false
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "按钮名称",
      prop: "menuName"
    },
    {
      label: "按钮标识",
      prop: "menuCode"
    },
    {
      label: "操作",
      fixed: "right",
      width: 220,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  function handleUpdate(row) {
    console.log(row);
  }

  const handleDelete = async row => {
    await delMenu(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    let tempForm = { ...form };
    tempForm["menuTypeList"] = [tabType.value == 1 ? 2 : 4];
    const { data } = await getMenuList(tempForm);
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.parentId = null;
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect(treeData) {
    let { id, selected, menuName } = treeData;
    form.parentId = selected ? id : null;
    currentTreeData.id = selected ? id : null;
    currentTreeData.menuName = selected ? menuName : null;
    currentTreeData.isLeaf = !treeData.children;
    onSearch();
  }

  function openDialog(title = "新增", optType = 1, row?: FormItemProps) {
    // 转换按钮 menuType  tabType: 1:  optType: 1:菜单  2: 按钮
    let menuType = tabType.value;
    if (optType == 2) {
      menuType = tabType.value == 1 ? 2 : 4;
    }
    console.log("tabType", tabType.value);
    console.log("menuType", menuType);

    // 判断是否是新增子级菜单和子级按钮，处理对应参数
    let parentId = row?.parentId ?? 0;
    let parentName = "";
    if (title === "新增" && row?.id) {
      parentId = row.id;
      parentName = row.menuName;
      row.menuName = "";
      row.menuCode = "";
      row.menuIcon = "";
      row.menuUri = "";
      row.id = null;
      row.sort = null;
      row.menuStatus = null;
    }

    // 如果是新增按钮，则把父级id赋值
    if (title === "新增" && [2, 4].includes(menuType)) {
      if (!currentTreeData.id) {
        return message("请选择所属菜单", { type: "warning" });
      }
      parentId = currentTreeData.id;
      parentName = currentTreeData.menuName;
    }

    // 处理 tree，禁用本身
    let newTreeData = null;
    if (title == "编辑" && optType == 1) {
      newTreeData = cloneDeep(treeData.value);
      treeFor: for (let index = 0; index < newTreeData.length; index++) {
        const v = newTreeData[index];
        if (!v.children) {
          continue;
        }

        for (let indexs = 0; indexs < v.children.length; indexs++) {
          const i = v.children[indexs];
          if (i.id == row.id) {
            i.disabled = true;
            break treeFor;
          }
        }
      }
      newTreeData.unshift({
        value: 0,
        id: 0,
        label: "一级菜单",
        menuName: "一级菜单"
      });
    }

    let titlePre = `${[1, 3].includes(menuType) ? "菜单" : "按钮"}`;
    addDialog({
      title: title + titlePre,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          title,
          titlePre,
          parentId,
          parentName,
          menuName: row?.menuName ?? "",
          menuIcon: row?.menuIcon ?? "",
          menuType, // 类型 1平台端菜单 2平台端按钮 3店长端菜单 4店长端按钮
          menuUri: row?.menuUri ?? "",
          menuCode: row?.menuCode ?? "",
          sort: row?.sort ?? "",
          menuStatus: row?.menuStatus ?? 1
        },
        treeData: newTreeData || treeData.value
      },
      width: "600px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message("操作成功", {
            type: "success"
          });
          done(); // 关闭弹框
        }
        FormRef.validate(async valid => {
          if (valid) {
            let reqData = { ...curData };
            delete reqData.title;
            delete reqData.titlePre;
            delete reqData.parentName;
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              await addMenu(reqData);
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              await upMenu(reqData);
              chores();
            }
            // 更新菜单
            if ([1, 3].includes(reqData.menuType)) {
              loadTree();
            } else {
              onSearch(); // 刷新表格数据
            }
          }
        });
      }
    });
  }

  /** 加载菜单tree */
  const loadTree = async () => {
    treeLoading.value = true;
    // 获取菜单
    let params = {
      menuTypeList: [tabType.value],
      pageNum: 1,
      pageSize: 200
    };
    const { data } = await getMenuList(params);
    treeData.value = handleTree(data.records || []);
    treeLoading.value = false;
    // 默认选择第一个
    // nextTick(() => {
    //   let tempData = treeData.value[0];
    //   if (tempData.children && tempData.children.length > 0) {
    //     let childData = tempData.children[0];
    //     form.parentId = childData.id;
    //     currentTreeData.id = childData.id;
    //     currentTreeData.menuName = childData.menuName;
    //     treeRef && treeRef.value.setCurrentKey(childData.id);
    //   }
    // });
  };

  const initData = async () => {
    loadTree();
    onSearch();
  };

  onMounted(() => {
    if (treeRef) {
      initData();
    }
  });

  watch(tabType, () => {
    if (!treeRef) {
      return;
    }
    console.log("watch");
    form.parentId = null;
    form.pageNum = 1;
    form.pageSize = 10;
    currentTreeData.id = null;
    currentTreeData.menuName = "";
    currentTreeData.isLeaf = null;
    treeRef.value.onTreeReset();
    initData();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    currentTreeData,
    tabType,
    deviceDetection,
    onSearch,
    loadTree,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
